<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package		CodeIgniter
 * @author		ExpressionEngine Dev Team
 * @copyright	Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Router Class
 *
 * Parses URIs and determines routing
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @author		ExpressionEngine Dev Team
 * @category	Libraries
 * @link		http://codeigniter.com/user_guide/general/routing.html
 */
class CI_Router {

	/**
	 * Config class
	 *
	 * @var object
	 * @access public
	 */
	var $config;
	/**
	 * List of routes
	 *
	 * @var array
	 * @access public
	 */
	var $routes			= array();
	/**
	 * List of error routes
	 *
	 * @var array
	 * @access public
	 */
	var $error_routes	= array();
	/**
	 * Current class name
	 *
	 * @var string
	 * @access public
	 */
	var $class			= '';
	/**
	 * Current method name
	 *
	 * @var string
	 * @access public
	 */
	var $method			= 'index';	
        /**
	 * Modules that contains the requested controllers, views, models.
	 *
	 * @var string
	 * @access public
	 */
	var $module		= '';
        /**
	 * Whether we access to the admincp or not
	 *
	 * @var boolean
	 * @access public
	 */
	var $is_admincp		= false;
        /**
	 * Default module 
	 *
	 * @var string
	 * @access public
	 */
	var $default_module;

	/**
	 * Constructor
	 *
	 * Runs the route mapping function.
	 */
	function __construct()
	{
		$this->config =& load_class('Config', 'core');
		$this->uri =& load_class('URI', 'core');
		log_message('debug', "Router Class Initialized");
	}

	// --------------------------------------------------------------------

	/**
	 * Set the route mapping
	 *
	 * This function determines what should be served based on the URI request,
	 * as well as any "routes" that have been set in the routing config file.
	 *
	 * @access	private
	 * @return	void
	 */
	function _set_routing()
	{
		// Are query strings enabled in the config file?  Normally CI doesn't utilize query strings
		// since URI segments are more search-engine friendly, but they can optionally be used.
		// If this feature is enabled, we will gather the module/class/method a little differently
		$segments = array();
		if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('module_trigger')]))
		{
			if (isset($_GET[$this->config->item('module_trigger')]))
			{
				$this->set_module(trim($this->uri->_filter_uri($_GET[$this->config->item('module_trigger')])));
				$segments[] = $this->fetch_module();
			}

			if (isset($_GET[$this->config->item('controller_trigger')]))
			{
				$this->set_class(trim($this->uri->_filter_uri($_GET[$this->config->item('controller_trigger')])));
				$segments[] = $this->fetch_class();
			}

			if (isset($_GET[$this->config->item('function_trigger')]))
			{
				$this->set_method(trim($this->uri->_filter_uri($_GET[$this->config->item('function_trigger')])));
				$segments[] = $this->fetch_method();
			}
		}

		// Load the routes.php file.
		if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/routes.php'))
		{
			include(APPPATH.'config/'.ENVIRONMENT.'/routes.php');
		}
		elseif (is_file(APPPATH.'config/routes.php'))
		{
			include(APPPATH.'config/routes.php');
		}

		$this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route;
		unset($route);
                // Set the default module so we can display it in the event
		// the URI doesn't correlated to a valid module.
		$this->default_module = (!isset($this->routes['default_module']) OR $this->routes['default_module'] == '') ? FALSE : strtolower($this->routes['default_module']);
                
		// Were there any query string segments?  If so, we'll validate them and bail out since we're done.
		if (count($segments) > 0)
		{
			return $this->_validate_request($segments);
		}

		// Fetch the complete URI string
		$this->uri->_fetch_uri_string();
                
		// Is there a URI string? If not, the default controller specified in the "routes" file will be shown.
		if ($this->uri->uri_string == '')
		{
                        return $this->_set_default_module();
		}

		// Do we need to remove the URL suffix?
		$this->uri->_remove_url_suffix();

		// Compile the segments into an array
		$this->uri->_explode_segments();

		// Parse any custom routing that may exist
		$this->_parse_routes();

		// Re-index the segment array so that it starts with 1 rather than 0
		$this->uri->_reindex_segments();
	}

        /**
	 * Set the default controller
	 *
	 * @access	private
	 * @return	void
	 */
	function _set_default_module()
	{
		if ($this->default_module === FALSE)
		{
			show_error("Unable to determine module should be displayed. A default module route has not been specified in the routing file.");
		}
		// Is the controller and method being specified?
                $default_module_segment = explode('/', $this->default_module);
                
                $this->set_module($default_module_segment[0]);
                
                if(empty($default_module_segment[1]))
                {
                    $default_module_segment[1] = 'index';
                }
                
                $this->set_class($default_module_segment[1]);
                
                if(empty($default_module_segment[2]))
                {
                    $default_module_segment[2] = 'index';
                }
                
                $this->set_method($default_module_segment[2]);
		$this->_set_request($default_module_segment);
		// re-index the routed segments array so it starts with 1 rather than 0
		$this->uri->_reindex_segments();

		log_message('debug', "No URI present. Default module set.");
	}
	// --------------------------------------------------------------------

	/**
	 * Set the Route
	 *
	 * This function takes an array of URI segments as
	 * input, and sets the current class/method
	 *
	 * @access	private
	 * @param	array
	 * @param	bool
	 * @return	void
	 */
	function _set_request($segments = array())
	{
		$segments = $this->_validate_request($segments);
                
		if (count($segments) == 0)
		{
			return $this->_set_default_module();
		}

                $this->set_module($segments[0]);
                
                //In case use admincp. 
                //We must increase index array one to get controllers in the next index.
                $isAdmincp = 0;
                
                if(!empty($segments[1]) && $segments[1] == 'admincp')
                {
                    $this->is_admincp = true;
                    $isAdmincp = 1;
                }
                
                if(empty($segments[1 + $isAdmincp]))
                {
                    $segments[1 + $isAdmincp] = 'index';
                }
                
		$this->set_class($segments[1 + $isAdmincp]);
                
                if(empty($segments[2 + $isAdmincp]))
                {
                    $segments[2 + $isAdmincp] = 'index';
                }
                
                $this->set_method($segments[2 + $isAdmincp]);
		// Update our "routed" segment array to contain the segments.
		// Note: If there is no custom routing, this array will be
		// identical to $this->uri->segments
		$this->uri->rsegments = $segments;
	}

	// --------------------------------------------------------------------

	/**
	 * Validates the supplied segments.  Attempts to determine the path to
	 * the controller.
	 *
	 * @access	private
	 * @param	array
	 * @return	array
	 */
	function _validate_request($segments)
	{
            //not input module.
		if (count($segments) == 0)
		{
			return $segments;
		}
                
                //Input module.
                if(is_dir(APPPATH . 'modules/' . $segments[0]))
                {
                    $this->set_module($segments[0]);
                    //Use segment check to get sub from the orgin segment. Segment check use for validate.
                    $segments_check = array_slice($segments, 1);
                    
                    if(count($segments_check) > 0)
                    {
                        if ($segments_check[0] != 'admincp') 
                        {
                            if (file_exists(APPPATH.'modules/'. $this->fetch_module() .'/controllers/'.$segments_check[0].'.php'))
                            {
                                    return $segments;
                            }
                            //else controller not exist
                            show_404($segments_check[0]);
                        }
                        else 
                        {
                            $segments_check = array_slice($segments_check, 1);
                            if(count($segments_check) > 0)
                            {
                                if(file_exists(APPPATH . 'modules/' . $this->fetch_module() . '/controllers/admincp/' . $segments_check[0] . '.php'))
                                {
                                    return $segments;
                                }
                                show_404($segments_check[0]);
                            }
                            else 
                            {
                                if(file_exists(APPPATH . 'modules/' . $this->fetch_module() . '/controllers/admincp/index.php'))
                                {
                                    return $segments;
                                }
                                
                                show_404('index');
                            }
                        }
                    }
                    else
                    {
                        if(file_exists(APPPATH.'modules/'. $this->fetch_module() .'/controllers/index.php'))
                        {
                            return $segments;
                        }
                        show_404('index');
                    }
                    
                    return $segments;
                }
                // If no exist this module
		if ( ! empty($this->routes['404_override']))
		{
			$err_uri_segment = explode('/', $this->routes['404_override']);
                        $this->set_module($err_uri_segment[0]);
			$this->set_class(!empty($err_uri_segment[1]) ? $err_uri_segment[1] : 'index');
			$this->set_method(!empty($err_uri_segment[2]) ? $err_uri_segment[2] : 'index');

			return $err_uri_segment;
		}

		// If no exist the module and no exist error module.
		show_404($segments[0]);
	}

	// --------------------------------------------------------------------

	/**
	 *  Parse Routes
	 *
	 * This function matches any routes that may exist in
	 * the config/routes.php file against the URI to
	 * determine if the class/method need to be remapped.
	 *
	 * @access	private
	 * @return	void
	 */
	function _parse_routes()
	{
		// Turn the segment array into a URI string
		$uri = implode('/', $this->uri->segments);

		// Is there a literal match?  If so we're done
		if (isset($this->routes[$uri]))
		{
			return $this->_set_request(explode('/', $this->routes[$uri]));
		}

		// Loop through the route array looking for wild-cards
		foreach ($this->routes as $key => $val)
		{
			// Convert wild-cards to RegEx
			$key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));

			// Does the RegEx match?
			if (preg_match('#^'.$key.'$#', $uri))
			{
				// Do we have a back-reference?
				if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE)
				{
					$val = preg_replace('#^'.$key.'$#', $val, $uri);
				}

				return $this->_set_request(explode('/', $val));
			}
		}

		// If we got this far it means we didn't encounter a
		// matching route so we'll set the site default route
		$this->_set_request($this->uri->segments);
	}

	// --------------------------------------------------------------------

	/**
	 * Set the class name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */
	function set_class($class)
	{
		$this->class = str_replace(array('/', '.'), '', $class);
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch the current class
	 *
	 * @access	public
	 * @return	string
	 */
	function fetch_class()
	{
		return $this->class;
	}

	// --------------------------------------------------------------------

	/**
	 *  Set the method name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */
	function set_method($method)
	{
		$this->method = $method;
	}

	// --------------------------------------------------------------------

	/**
	 *  Fetch the current method
	 *
	 * @access	public
	 * @return	string
	 */
	function fetch_method()
	{
		if ($this->method == $this->fetch_class())
		{
			return 'index';
		}

		return $this->method;
	}

	// --------------------------------------------------------------------
        
        /**
	 *  Set the module name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */
	function set_module($mod)
	{
		//$this->module = str_replace(array('/', '.'), '', $mod).'/';
            $this->module = str_replace(array('/', '.'), '', $mod);
	}

	// --------------------------------------------------------------------

	/**
	 *  Fetch the module that contains the requested controller class
	 *
	 * @access	public
	 * @return	string
	 */
	function fetch_module()
	{
		return $this->module;
	}

	// --------------------------------------------------------------------

	/**
	 *  Set the controller overrides
	 *
	 * @access	public
	 * @param	array
	 * @return	null
	 */
	function _set_overrides($routing)
	{
		if ( ! is_array($routing) || empty($routing['module']))
		{
			return;
		}

                $this->set_module($routing['module']);

		if (empty($routing['controller']))
		{
                    $routing['controller'] = 'index';
		}
                
                $this->set_class($routing['controller']);
                
		if (empty($routing['function']))
		{
			$routing['function'] = 'index';
		}
                
                $this->set_method($routing['function']);
	}


}
// END Router Class

/* End of file Router.php */
/* Location: ./system/core/Router.php */